uniform sampler2D suggestiveContourTexture, depthTexture;
uniform vec2 screenSize;
uniform bool useSmoothstep;
uniform float smoothstepStart, smoothstepEnd;
uniform vec4 color;
           
void main(void) { 
 
  float pixel;
  float depth;
  float minDepth= 1.0;
  float center= texture2D(suggestiveContourTexture, gl_FragCoord.xy/screenSize).x;
  float centerDepth= texture2D(depthTexture, gl_FragCoord.xy/screenSize).x;
  float max= 0.0;
  float darker= 0.0;
  float numPixels= 9.0; 
  int i;

  vec2 offsets[8];
  
  offsets[0]= vec2(-1.0, -1.0);
  offsets[1]= vec2(-1.0,  0.0);
  offsets[2]= vec2(-1.0,  1.0);
  offsets[3]= vec2( 0.0, -1.0);
  offsets[4]= vec2( 0.0,  1.0);
  offsets[5]= vec2( 1.0, -1.0);
  offsets[6]= vec2( 1.0,  0.0);
  offsets[7]= vec2( 1.0,  1.0);	
  

  for(i=0; i<8; i++){
    pixel = texture2D(suggestiveContourTexture, (gl_FragCoord.xy+offsets[i])/screenSize).r;
    if(pixel<center) darker++;
    if(pixel>max) max= pixel;
    if(centerDepth==1.0){
      depth= texture2D(depthTexture, (gl_FragCoord.xy+offsets[i])/screenSize).x; 	
      if(depth<minDepth) minDepth= depth;
    }
  }  

  float alpha= (1.0-(darker/numPixels))*(max-center)*color.a;  
  if(useSmoothstep) alpha= smoothstep(smoothstepStart, smoothstepEnd, alpha);
  gl_FragColor= vec4(alpha, alpha, alpha, 1.0);
  if(centerDepth==1.0) gl_FragDepth= minDepth;
  else gl_FragDepth= gl_FragCoord.z;	

  //gl_FragColor= vec4(texture2D(suggestiveContourTexture, (gl_FragCoord.xy)/screenSize).xyz, 1.0);
}